<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <tips optionTemplate="developmentDeviceList"></tips>
      <div class="hearder-search">
        <el-col :span="24" class="breadcrumb-container input-val-box">
          <el-button type="primary" size="small" @click="addDevice(0)">新增设备管理</el-button>
          <el-button size="small" @click="refreshFn"><i class="el-icon-refresh"></i>刷新</el-button>
          <span class="allbook">总 {{ page.total }} 条数据</span>
        </el-col>
      </div>
      <!--本体列表，数据 -->
      <div class="table-body">
        <div class="table-body-box">
          <el-table
              ref="multipleTable"
              :data="arryList"
              :stripe="tableStyle.tableStripe"
              :border="tableStyle.tableBorder"
              tooltip-effect="dark"
              style="width: 100%"
              header-cell-class-name="table-text-c"
              cell-class-name="table-text-c">
            <el-table-column
                label="设备名称"
                prop="name">
            </el-table-column>
            <el-table-column
                label="设备号"
                prop="id_code">
            </el-table-column>
            <el-table-column
                label="设备IP"
                prop="ip">
            </el-table-column>
            <el-table-column
              label="归属"
              align="center">
              <template slot-scope="scope">
                {{ schoolData[scope.row.school_id] && schoolData[scope.row.school_id].name }}
              </template>
            </el-table-column>
            <el-table-column
              label="App状态">
              <template slot-scope="scope">
                <el-link>暂无</el-link>
<!--                <el-link type="success">在线</el-link>-->
<!--                <el-link type="danger">离线</el-link>-->
              </template>
            </el-table-column>
            <el-table-column
              label="最后访问时间"
              prop="last_time">
            </el-table-column>
            <el-table-column
                label="操作"
                width="300"
                fixed="right">
              <template slot-scope="scope">
                <el-button size="small" @click="addDevice(scope.row.id)">编辑设备详情</el-button>
<!--                <el-button size="small" @click="getVersion(scope.row.id)">版本管理</el-button>-->
<!--                <el-button size="small" @click="getVersionFn('device',scope.row.ip)">更新设备</el-button>-->
<!--                <el-button size="small" @click="getVersionFn('communicator', scope.row.ip)">更新通讯器</el-button>-->
                <el-button size="small" @click="facilityId=scope.row.id,errorVisible=true">错误记录</el-button>
                <el-button size="small" @click="detelFn(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!--工具条 分页-->
      <el-col :span="24" class="toolbar">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="page.total"
            :page-size="page.pagesize"
            @current-change="handleSizeChange">
        </el-pagination>
      </el-col>
    </div>
    <versions :visible.sync="versionsVisible" :facilityId="facilityId"></versions>
    <editDevice :visible.sync="versionsEditVisible" :facilityId="facilityId"></editDevice>
    <errorList :visible.sync="errorVisible" :facilityId="facilityId"></errorList>
  </div>
</template>

<script>
import {pagination, tableoption} from '@/utils/util.js'
import versions from "./versions";
import editDevice from "./editDevice";
import errorList from "./errorList";
import {schoolIndex} from '@/api/admin/system'

export default {
  components: {
    versions,
    editDevice,
    errorList
  },
  data() {
    return {
      versionsEditVisible: false,
      versionsVisible: false,
      errorVisible:false,
      arryList: [], // 页面数据列表
      // 设置table样式
      tableStyle: tableoption,
      // 设置table页面分页所需
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      editOption: {
        name: '',
        id_code: '',
        ip: '',
      },
      facilityId: 0,
      facilityTime: '',
     schoolData: {}
    }
  },
  created() {
    localStorage.removeItem("uploadTimeNew")
    this.InitFn()
    this.schoolIndexFn()
    // this.facility_ip_Fn()
  },
  methods: {
    // 初始化
    InitFn() {
      let n = this;
      // 0待审核1审核2驳回 is_examine
      this.$post(this.api.Developmental.faceFacility.index, {
        p: this.page.pageindex
      }).then((response) => {
        if (response.code === 0) {
          let array_ = []
          for (let i in response.list.data) {
            response.list.data[i].status = false;
            response.list.data[i].statusWord = '--';
            array_.push(n.changeData(response.list.data[i]))
          }
          this.arryList = array_;
          this.page.total = response.list.total;
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // async facility_ip_Fn() {
    //   let data = await this.$fetch(this.api.student.studentPoint, {
    //     student_id: this.studentId
    //   })
    // },
    getVersionFnUpload(type, ip) {
      let that = this;
      let url = ip + ':5000/api/up_data';
      if (type === 'communicator') {
        url = ip + ':5000/api/init_respberry';
      }
      this.$deviceFn(url, {}).then((response) => {
        console.log('response:', response)
        if (response.status === 200) {
          // if (response.data.code === 200) {
          //   // 需要5秒时间更新
          //   // Math.abs(time1 - time2) >= (5 * 60 * 1000) //time1, time2为时间戳
          //   that.$message.success('更新成功！')
          //   that.InitFn()
          // }
          that.$message.success('App ip连接成功，数据更新请在APP端确认！')
          that.InitFn()
        } else {
          // that.$message.success('更新失败！'+response.data)
          that.$confirm('更新失败！' + response.data, '错误提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            showCancelButton: false
          }).then(() => {
          }).catch(() => {
          });
        }
      }).catch((err) => {
        // 服务器没连接，ip不存在
        that.$confirm('ip请求超时，请确认ip是否正确，请确认此设备ip是否在线！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showCancelButton: false
        }).then(() => {
        }).catch(() => {
        });
      })
    },
    getVersionFn(type, ip) {
      // type communicator 通讯器 device 设备 uploadTime
      // Math.abs(time1 - time2) >= (5 * 60 * 1000) //time1, time2为时间戳
      // localStorage.setItem("stor");
      // localStorage.setItem("uploadTime", tmp);
      let uploadTime = 5; // 更新间隔
      let tmp = Date.parse(new Date()).toString();
      let timeType = {};
      tmp = tmp.substr(0, 10);
      console.log('getTime[type]', localStorage.getItem("uploadTimeNew"))
      if (!localStorage.getItem("uploadTimeNew")) {
        timeType[type] = tmp
        console.log('保存被容：', timeType)
        localStorage.setItem("uploadTimeNew", JSON.stringify(timeType));
        this.getVersionFnUpload(type, ip)
      } else {
        let getTime = JSON.parse(localStorage.getItem("uploadTimeNew"));
        if (!getTime[type]) {
          getTime[type] = tmp
          localStorage.setItem("uploadTimeNew", JSON.stringify(getTime));
          this.getVersionFnUpload(type, ip)
          return
        }
        console.log('getTime[type]', getTime)
        let time_ = this.calculateDiffTime(getTime[type])
        time_ = time_.split('-')
        console.log('时间', time_)
        if (Number(time_[0]) || Number(time_[1]) || Number(time_[2])) {
          console.log('进行更新')
          timeType[type] = tmp
          localStorage.setItem("uploadTimeNew", JSON.stringify(timeType)); // 设置新的时间
          this.getVersionFnUpload(type, ip)
        } else {
          if (Number(time_[3]) > uploadTime) {
            console.log('查验秒数可以更新')
            timeType[type] = tmp
            localStorage.setItem("uploadTimeNew", JSON.stringify(timeType)); // 设置新的时间
            this.getVersionFnUpload(type, ip)
          } else {
            console.log('不可以更新')
            this.$message.error('点击过于频繁，5秒后再来更新')
          }
        }
      }
    },
    calculateDiffTime(start_time) {
      console.log('start_time:', start_time)
      if (!parseInt(start_time)) return "-";
      var endTime = Math.round(new Date() / 1000);
      console.log('endTime:', endTime)
      var timeDiff = (endTime - start_time) * 1000
      var days = Math.floor(timeDiff / (24 * 3600 * 1000));
      var leave1 = timeDiff % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / (3600 * 1000));
      //计算相差分钟数
      var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / (60 * 1000));

      //计算相差秒数

      var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
      var seconds = Math.round(leave3 / 1000);
      return days + '-' + hours + '-' + minutes + '-' + seconds
    },
    refreshFn() {
      this.page.pageindex = 1;
      this.InitFn()
    },
    changeData(option) {
      return JSON.parse(JSON.stringify(option))
    },
    // 分页
    handleSizeChange(val) {
      this.page.pageindex = val
      this.InitFn()
    },
    getVersion(id) {
      this.facilityId = id
      this.versionsVisible = true
    },
    addDevice(option) {
      this.facilityId = option
      this.versionsEditVisible = true
    },
    detelFn(id) {
      let self_ = this;
      this.$confirm('此设备将删除，确认删除此信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self_.$post(this.api.Developmental.faceFacility.delete, {
          id: id
        }).then((response) => {
          if (response.code === 0) {
            this.InitFn()
            this.$message.success(response.msg)
          } else {
            this.$message.error(response.msg)
          }
        }).catch((err) => {
          console.log(err)
        })
      }).catch(() => {

      })
    },
    schoolIndexFn() {
      schoolIndex().then(res => {
        let schoolData_ = {
          0: {id: 0, name: '其他'}
        }
        for (let item of res.list) {
          schoolData_[item.id] = item
        }
        this.schoolData = schoolData_
      })
    },
  },
  mounted() {
  },
  // 离开当前页面后执行
  destroyed() {
  }
}
</script>
